package edu.uci.ics.multicast;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;

public class ThreadReceiveForwardStreaming implements Runnable {

	private static final int STREAMING_PORT = 52222;
	
	private Thread myThread = null;
	private List<Socket> listSocketChildren = null;
	private Socket fatherSocket = null;
	
	public ThreadReceiveForwardStreaming(String fatherHostName, List<Socket> listSocketChildren) {
		this.listSocketChildren = listSocketChildren;
		this.myThread = new Thread(this);
		try {
			this.fatherSocket = new Socket(fatherHostName, STREAMING_PORT);
			System.err.println("Connection openned with "+fatherHostName+" port "+STREAMING_PORT);
		} catch (IOException e) {
			e.printStackTrace(System.err);
		}
	}
	
	public void run() {
		while(true) {
			try {
				ObjectInputStream sockInput = new ObjectInputStream(fatherSocket.getInputStream());
		        String data = (String) sockInput.readObject();
		        System.out.println("Peer:" + InetAddress.getLocalHost().getHostAddress() + " received data:"+data);
				for (Socket sock : listSocketChildren) {
					ObjectOutputStream sockOutput = new ObjectOutputStream(sock.getOutputStream());
					sockOutput.writeObject(data);
					sockOutput.flush();
				}
			}
			catch (Exception e){
				e.printStackTrace(System.err);
				return;
			}
		}
	}

	public void start() {
		myThread.start();
	}

}
